﻿using ConsoleApp.Valid.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp.Valid
{
    public class Validator
    {
        public static bool Validate<T>(T obj, out string errorMessage)
        {
            errorMessage = null;
            var type = typeof(T);
            var properties = type.GetProperties();

            foreach (var property in properties)
            {
                var validationAttributes = property.GetCustomAttributes(typeof(ValidationAttribute), true);

                foreach (var attribute in validationAttributes)
                {
                    var value = property.GetValue(obj);

                    switch (attribute)
                    {
                        case RequiredAttribute required:
                            if (value == null || (value is string str && string.IsNullOrWhiteSpace(str)))
                            {
                                errorMessage = required.ErrorMessage;
                                return false;
                            }
                            break;
                        case RangeAttribute range:
                            if (value is IComparable comparable)
                            {
                                if (comparable.CompareTo(range.Minimum) < 0 || comparable.CompareTo(range.Maximum) > 0)
                                {
                                    errorMessage = string.Format(range.ErrorMessage, range.Minimum, range.Maximum);
                                    return false;
                                }
                            }
                            break;
                            // 可以添加更多校验特性类型  
                    }
                }
            }

            return true;
        }
    }
}
